<?php

namespace App\Http\Controllers;

use App\Models\Task;
use Exception;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class TasksController extends Controller
{
    protected function run_process($task)
    {
        try {
            $state = config('task.state', 'OFF');
            $url = config('task.url', 'http://localhost:8080');
            $data = [
                'task_id' => $task->id,
                'task_type' => intval($task->dev_type),
                'data_type' => 1,
                'data' => config('task.path', '/home/ubuntu/workspace/guantik/') . $task->filepath,
            ];
            if ('ON' == $state) {
                $resp = Http::post($url, $data);
                if ($resp->successful() && optional($resp->json())['code'] == 20202) {
                    $task->status = '运行中';
                } else {
                    $task->status = '失败';
                }
                $task->status_info = $resp->json();
            } else {
                $task->status = '未启动';
            }
        } catch (Exception $e) {
            $task->status_info = $e->getMessage();
        }
        $task->save();
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = Task::with('user')->requestCriteria($request)->paginate($request->query('limit'));
        return $this->respondSuccess($data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|max:50',
            'filepath' => 'required',
            'dev_type' => 'required|in:1,2,3,4'
        ], [
            'dev_type.in' => 'dev_type 取值 [1,2,3,4]',
        ]);

        try {
            $request['status'] = '运行中';
            $request['user_id'] = $request->user()->id;
            $task = Task::create($request->input());
            // $this->run_process($task);
            return $this->respondSuccess($task);
        } catch (QueryException $e) {
            return $this->respondError($e->getMessage());
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Task  $task
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request, Task $task)
    {
        $reports = $task->reports()->requestCriteria($request)->paginate($request->query('limit'));
        // $data = $reports->map(function ($item) {
        //     $new = collect($item)->merge($item->result);
        //     unset($new['result']);
        //     return $new;
        // });
        return $this->respondSuccess($reports);
    }


    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Task  $task
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Task $task)
    {
        $data = $request->only(['name', 'remarks']);
        $data = $task->update($data);
        return $this->respondSuccess($data);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Task  $task
     * @return \Illuminate\Http\Response
     */
    public function destroy(Task $task)
    {
        $data = $task->delete();
        return $this->respondSuccess($data);
    }
}
